﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;

using UploadManager;
//using StoreClientModule;
using UnityCore;

namespace MBB_Store_Sales_Report
{
    public partial class frmCashRegisteredList : Form
    {
        DataTable RecordTable = new DataTable();

        SynchronizeData sync = new SynchronizeData();
        Threader t = new Threader();
        readDetails path = new readDetails();

        DataTable exportCashRegistry = new DataTable();
        DataTable exportCheques = new DataTable();
        DataTable exportExpenses = new DataTable();

        double over = 0.0;
        double amt=0;
 
        public frmCashRegisteredList()
        {
            InitializeComponent();
            btnView.Click += new EventHandler(btnView_Click);
            btnClose.Click += new EventHandler(btnClose_Click);
            panel2.EnabledChanged += new EventHandler(panel2_EnabledChanged);
            btnPrint.Click +=new EventHandler(btnPrint_Click);

            sync.ProcessCompleted += new UnityCore.CoreHandler(sync_ProcessCompleted);
            sync.ProcessError += new UnityCore.CoreHandler(sync_ProcessError);
        }

        void sync_ProcessError(string pcode, string msg)
        {
            t.SafeCall(this, delegate
            {
                MessageBox.Show(msg);
                pnlMsg.Visible = false;
            });
        }
        void sync_ProcessCompleted(string pcode, string msg)
        {
            t.SafeCall(this, delegate
            {
                switch (pcode)
                {
                    case "GetStores":
                        cmbStore.Items.AddRange(sync.stores);
                        break;
                    case "ReadMany":
                        if (sync.exportTables.Count > 0)
                        {
                            pnlMsg.Visible = false;
                            if (sync.exportTables[0].DefaultView.ToTable().Rows.Count > 0)
                                exportCashRegistry = sync.exportTables[0].DefaultView.ToTable(true, "fDenomination", "fPcs");
                            if(sync.exportTables[1].DefaultView.ToTable().Rows.Count > 0)
                                exportCheques = sync.exportTables[1].DefaultView.ToTable(true, "fAmount");
                            if (sync.exportTables[2].DefaultView.ToTable().Rows.Count > 0)
                                exportExpenses = sync.exportTables[2].DefaultView.ToTable(true, "fExpensesType", "fExpensesAmount");

                            denoGrid.DataSource = exportCashRegistry;

                            exportCashRegistry.Columns[0].ColumnName = "Denomination";
                            exportCashRegistry.Columns[1].ColumnName = "Pcs";
                            exportCashRegistry.Columns.Add("Amount");

                            denoGrid.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

                            displayData();
                        }
                        
                        
                        break;
                }

            });
        }

        void displayData()
        {
            over = double.Parse(sync.exportTables[0].Rows[0]["fOver"].ToString());
            txtOver.Text = Common.FormatCurrency(over);

            for (int i = 0; i < denoGrid.Rows.Count; i++)
            {
                double amount = 0;

                if (denoGrid.Rows[i].Cells["Denomination"].Value.Equals("Coins"))
                    amount = 1 * double.Parse(denoGrid.Rows[i].Cells["Pcs"].Value.ToString());
                else
                    amount = double.Parse(denoGrid.Rows[i].Cells["Denomination"].Value.ToString()) * double.Parse(denoGrid.Rows[i].Cells["Pcs"].Value.ToString());
                
                denoGrid.Rows[i].Cells["Amount"].Value = Common.FormatCurrency(amount);
                amt += amount;
            }
            double totalC = 0.0;
            //cheques
            for (int i = 0; i < exportCheques.Rows.Count; i++)
            {
                double amtC = double.Parse(exportCheques.Rows[i]["fAmount"].ToString());
                totalC += amtC;
            }

            //expenses
            double totalEa= 0, totalEb=0;
            for (int i = 0; i < exportExpenses.Rows.Count; i++)
            {
                if (exportExpenses.Rows[i]["fExpensesType"].ToString().Equals("B"))
                {
                    double amtEb = double.Parse(exportExpenses.Rows[i]["fExpensesAmount"].ToString());
                    totalEb += amtEb;
                }
                else
                {
                    double amtEa = double.Parse(exportExpenses.Rows[i]["fExpensesAmount"].ToString());
                    totalEa += amtEa;
                }
            }
            txtCheck.Text = Common.FormatCurrency(totalC);
            txtTotal.Text = Common.FormatCurrency(amt);
            txtExpensesA.Text = Common.FormatCurrency(totalEa);
            txtExpensesB.Text = Common.FormatCurrency(totalEb);

            double grandTotal = amt + totalC + totalEa + totalEb;
            txtTotalCashRegistered.Text = Common.FormatCurrency(grandTotal);
        }

        
        void btnView_Click(object sender, EventArgs e)
        {
            if (txtDate.Text != "" && cmbStore.Text != "")
            {
                pnlMsg.Visible = true;
                path.date = txtDate.Text;
                path.remNode = cmbStore.Text;
                path.fileNames.Clear();
                path.fileNames.Add("Cash Registry");
                path.fileNames.Add("Cheques");
                path.fileNames.Add("Expenses");
                sync.ReadMany(path);
            }
        }
        void panel2_EnabledChanged(object sender, EventArgs e)
        {
            if (!panel2.Enabled)
            {
                panel2.BackColor = Color.MidnightBlue;
            }
            else
            {
                panel2.BackColor = Color.RoyalBlue;
            }
        }
        void btnClose_Click(object sender, EventArgs e)
        {
            pnlCashRegistered.Dispose();
            this.Dispose();
        }
        public Panel PanelForm
        {
            get { return pnlCashRegistered; }
        }
        public void Initialize(string Title)
        {
            this.Select();
            lblText.Text = Title;

            sync.Stores();
            path.fileNames = new List<string>();
            
        }

        
        void btnPrint_Click(object sender, EventArgs e)
        {
            PrintDocument pd = new PrintDocument();
            pd.DocumentName = lblText.Text;
            pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
            PrintDialog pdlg = new PrintDialog();
            pdlg.Document = pd;
            if (pdlg.ShowDialog() == DialogResult.OK)
            {
                PrintPreviewDialog ppdlg = new PrintPreviewDialog();
                ppdlg.Document = pd;
                //Tracking.EnterLog("Price Table is printed.", DateTime.Now.ToString());
                ppdlg.ShowDialog();
            }
        }

        void pd_PrintPage(object sender, PrintPageEventArgs e)
        {
            //printing
            int cnt = 0;
            int pp = 1;
            float lpp = 0;
            float y = 0;
            float tm = e.MarginBounds.Top;
            float lm = e.MarginBounds.Left;
            float rm = e.PageBounds.Width - 150;
            float bm = e.PageBounds.Height - 100;
            float ht = 0;
            Font cFont;
            StringFormat sf = new StringFormat();


            //Header
            y = 150;
            cFont = new Font("Courier New", 12f, FontStyle.Bold);
            ht = cFont.GetHeight(e.Graphics);
            sf.Alignment = StringAlignment.Center;
            e.Graphics.DrawString(cmbStore.Text, new Font("Courier New", 15f, FontStyle.Bold), Brushes.Black, e.PageBounds.Width / 2, 50, sf);
            e.Graphics.DrawString(Common.lStoreAddress, new Font("Courier New", 15f, FontStyle.Bold), Brushes.Black, e.PageBounds.Width / 2, 70, sf);
       
            sf.Alignment = StringAlignment.Near;
            e.Graphics.DrawString("A. Cash Denomination", cFont, Brushes.Black, lm, y, sf);
            sf.Alignment = StringAlignment.Far;
            e.Graphics.DrawString(txtDate.Text, cFont, Brushes.Black, rm + 100, y, sf);
            //Column Header
            y += ht;

            e.Graphics.FillRectangle(Brushes.LightGray, lm, y, 350, ht);
            e.Graphics.DrawRectangle(new Pen(Brushes.Black), lm, y, 350, ht);
            sf.Alignment = StringAlignment.Center;
            float cx = lm + (((rm - lm) * 25) / 100);
            float tx = lm + (((rm - lm) * 12.5f) / 100);
            e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
            e.Graphics.DrawString("Denomination", cFont, Brushes.Black, tx, y, sf);

            cx += ((rm - lm) * 10) / 100;
            tx = cx - ((rm - lm) * 10) / 200;
            e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
            e.Graphics.DrawString("pcs", cFont, Brushes.Black, tx, y, sf);

            tx += ((rm - lm) * 25) / 200;
            e.Graphics.DrawString("Amount", cFont, Brushes.Black, tx+20, y, sf);
            //Data
            y += ht * (1.5f);
            ht = cFont.GetHeight(e.Graphics);
            lpp = (bm - y) / ht;
            int cl = 0;
            float stx = 0;

            while (cl <= lpp && cnt < denoGrid.Rows.Count)
            {
                sf.Alignment = StringAlignment.Near;
                stx = lm + 10;
                string str = denoGrid.Rows[cnt].Cells["Denomination"].Value.ToString();          
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);

                sf.Alignment = StringAlignment.Center;
                stx += ((rm - lm) * 30) / 100;
                str = denoGrid.Rows[cnt].Cells["pcs"].Value.ToString();

                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);
                stx += ((rm - lm) * 25) / 100;
                sf.Alignment = StringAlignment.Far;
                str = denoGrid.Rows[cnt].Cells["Amount"].Value.ToString();
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);
                
                y += ht;
                cnt++;
                cl++;
            }
            e.Graphics.DrawString("Total", cFont, Brushes.Blue, stx - 120, y + 10, sf);
            e.Graphics.DrawString(txtTotal.Text, cFont, Brushes.Blue, stx, y + 10, sf);

            sf.Alignment = StringAlignment.Near;

            ht = cFont.GetHeight(e.Graphics);
            y += 100;
            int x = 100;

            e.Graphics.DrawString("B. Expenses", cFont, Brushes.Black, x, y, sf);
            y += ht;
            x += 100;
            e.Graphics.DrawString("A1: Php "+txtExpensesA.Text, cFont, Brushes.Blue, x, y, sf);
            y += ht;
            e.Graphics.DrawString("A2: Php " + txtExpensesB.Text, cFont, Brushes.Blue, x, y, sf);
            x = 100;
            y += ht;
            e.Graphics.DrawString("C. Check", cFont, Brushes.Black, x, y, sf);
            y += ht;
            e.Graphics.DrawString("    Php " + txtCheck.Text, cFont, Brushes.Blue, x + 100, y, sf);

            y += 60;
            e.Graphics.DrawString("CASH REGISTERED:", cFont, Brushes.Black, x, y, sf);
            e.Graphics.DrawString("    Php " + Common.FormatCurrency((double.Parse(txtTotalCashRegistered.Text) + double.Parse(txtOver.Text))), cFont, Brushes.Blue, x + 130, y, sf);

            y += ht;
            e.Graphics.DrawString("Total: Php "+txtTotalCashRegistered.Text, cFont, Brushes.Blue, x+100, y, sf);
            e.Graphics.DrawString("       Php " + txtOver.Text, cFont, Brushes.Blue, x + 100, y + ht, sf);

            if (cnt < denoGrid.Rows.Count)
            {
                e.HasMorePages = true;
                pp++;
            }
            else
            {
                e.HasMorePages = false;
                cnt = 1;
                pp = 1;
            }
        }

    }
}
